import { _decorator, Component, Director, director, instantiate, js, Node } from 'cc';
import { EDITOR } from 'cc/env';
import { BaseComponent } from './BaseComponent';
const { ccclass, property } = _decorator;


export class UIManager {

    private constructor() {
        // director.once(Director.EVENT_AFTER_SCENE_LAUNCH, this.Init, this);
    }

    /** 初始化方法 */
    public Init(): void {
        this.Root = director.getScene().getChildByName('Canvas').getChildByName("UIManager");
    }


    /** 单例实例 */
    public static readonly instance: UIManager = new UIManager();

    //场景节点
    private Root: Node = null;

    //已添加场景
    private SceneList: Map<string, BaseComponent> = new Map();

    //当前场景
    private CurrentScene: BaseComponent | null = null;

    /**
     * 显示UI
     * @param 类名称
     */
    public ShowUI(_classname: string) {

        let view: BaseComponent = this.SceneList.get(_classname);
        const UIClass = js.getClassByName(_classname) as { new(): BaseComponent };

        if (!view) {
            const node: Node = instantiate(app.resManager.Prefabs[_classname]);
            view = node.getComponent(UIClass);
            this.SceneList.set(_classname, view);
        }

        console.log(this.CurrentScene)
        //如果有场景则隐藏掉
        if (this.CurrentScene) {
            this.CurrentScene.node.removeFromParent();
        }

        this.CurrentScene = view;

        this.CurrentScene.node.parent = this.Root;
        this.CurrentScene.node.setSiblingIndex(this.Root.children.length - 1);

    }

}


/** 导出单例实例 */
export const uiManager = UIManager.instance;
